package com.osc.exam.config;

import com.osc.exam.entity.domain.Permission;
import com.osc.exam.entity.domain.Role;
import com.osc.exam.entity.domain.User;
import com.osc.exam.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 权限配置
 */
public class EnceladusShiroRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 取登录用户
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Role role : user.getRoles()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getRoleName());
            //添加权限
            for (Permission permission : role.getPermission()) {
                simpleAuthorizationInfo.addStringPermission(permission.getName());
            }
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取用户信息
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        // 获取用户名
        User user = userService.findUserByName(userToken.getUsername());

        String name = user.getUsername();
        String password = user.getPassword();
        // 说明查无此人
        if (user == null) {
            return null;
        }
        // 密码认证,shiro做
        // 放入User对象
        return new SimpleAuthenticationInfo(user, password, "");
    }
}
